<?php

/**
 * 基础控制器基类
 */
namespace app\common\controller;

use \think\Controller;
use app\common\middleware\ThrottleMiddleware;
use app\common\component\ErrorCode;
use app\common\component\Filter;
use app\common\component\Authentication;

class Base extends Controller
{
    protected $backendUser = [];

    /**
     * 控制器初始化函数
     */
    public function _initialize()
    {
        /** 登录验证 */
        $authentication = new Authentication();
        $this->backendUser = $authentication->loginVerify() ? : [];
        /** ajax限流 */
        ThrottleMiddleware::getInstance()->accessLimit($this->request);
        /** ajax入参过滤*/
        Filter::getInstance()->paramValid($this->request);
    }

    /**
     * 所有web页面渲染方法
     * @param string $template
     * @param array $vars
     * @param array $replace
     * @param array $config
     * @return mixed
     */
    protected function show($template = '', $vars = [], $replace = [], $config = [])
    {
        $module_name = $this->request->module();
        $controller_name = $this->request->controller();
        $action_name = $this->request->action();
        if (empty($template)) {
            $template = $module_name . '/' . $controller_name . '/' . $action_name;
        }

	$scheme = $_SERVER['REQUEST_SCHEME'] ?? 'http';
	$scheme .= '://';
        $user_name = $this->backendUser ? $this->backendUser['nickname'] : '';
        $this->assign('current_page', $this->request->action());
        $this->assign('host_name', $scheme . config('environment.host_name'));
        $this->assign('template_path', $module_name . '/' . $controller_name . '/' . $action_name);
        $this->assign('user_name', $user_name);
        return $this->fetch($template, $vars, $replace, $config);
    }

    /**
     * 请求失败
     * @return string
     */
    protected function responseSuccess()
    {
        return $this->responseData([], ErrorCode::RESPONSE_SUCCESS,  '请求成功');
    }

    /**
     * 请求成功
     * @return string
     */
    protected function responseFail($message = '请求失败')
    {
        return $this->responseData([], ErrorCode::RESPONSE_FAIL,  $message);
    }

    /**
     * 响应返回数据给客户端
     * @param array $data
     * @return string
     */
    protected function responseData($data = [], $responseCode = ErrorCode::RESPONSE_SUCCESS, $message = '请求成功')
    {
        $responseData = [
            'responseCode' => $responseCode,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($responseData);
    }

    /**
     * 下载word文件
     * @param $filePath
     */
    protected function downloadWord($filePath)
    {
        $content = file_get_contents($filePath);
        ob_start();
        header("Cache-Control: public");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");

        if (strpos($_SERVER["HTTP_USER_AGENT"],'MSIE')) {
            header('Content-Disposition: attachment; filename=ueditor_word.docx');
        }else if (strpos($_SERVER["HTTP_USER_AGENT"],'Firefox')) {
            Header('Content-Disposition: attachment; filename=ueditor_word.docx');
        } else {
            header('Content-Disposition: attachment; filename=ueditor_word.docx');
        }

        header("Pragma:no-cache");
        header("Expires:0");
        echo $content;
        ob_end_flush();

        // 下载完成就移动文件
        $newFilepath = str_replace('.docx', '_already.docx', $filePath);
        copy($filePath, $newFilepath);
        unlink($filePath);
        exit();
    }
}
